package network_programming.chat;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    Socket socket;

    public Client() throws IOException {
        System.out.println("正在连接服务端...");
        socket = new Socket("localhost", 8088);
        System.out.println("连接成功");
    }

    public void start() throws IOException {
        try {
            //启动用来读去来自服务端发送过来消息的线程
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();


            //低级流,作用:将写出的字节发送给建立连接的远端计算机
            OutputStream out = socket.getOutputStream();
            //转换流(高级流),作用:1衔接字节与字符流   2将写出的字符转换为字节
            OutputStreamWriter osw
                    = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            //缓冲流(高级流),作用:块写文本数据加速
            BufferedWriter bw = new BufferedWriter(osw);
            //PrintWriter(高级流),作用:1按行写出字符串  2自动行刷新
            PrintWriter pw = new PrintWriter(bw,true);

            Scanner scanner = new Scanner(System.in);
            while(true) {
                String line = scanner.nextLine();
                if("exit".equals(line)){
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();//与服务端断开连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 该线程任务负责读取来自服务端发送过来的消息
     */
    private class ServerHandler implements Runnable{
        public void run() {
            //通过socket获取输入流,来读取远端计算机(服务端)发送过来的消息
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr
                        = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while((message = br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {

            }
        }
    }

    public static void main(String[] args) {
        try {
            Client client = new Client();
            client.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
